package com.github.utils;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

import androidx.core.content.FileProvider;

import com.github.logger.LoggerKt;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

/**
 * 分享 第三方相关工具类
 *
 * @author Mr.xie
 * @Date 2025/8/6
 */
public class ShareUtils {


    private final static String TAG = ShareUtils.class.getSimpleName();

    /**
     * 进入QQ群
     *
     * @param context 上下文对象
     */
    public static void shareQQGroup(Context context, String qqKey) {
        String url = "mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + qqKey;
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    public static void shareImage(Context context, Bitmap bitmap, String path, String shareCacheFileName, Runnable runnable) {
        try {
            // 构建图片缓存路径
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String imagePath = path + File.separator + shareCacheFileName;
            File cacheFile = new File(imagePath);
            if (!cacheFile.exists()) {
                cacheFile.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(cacheFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.WEBP, 100, bos);

            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            while (bis.available() > 0) {
                fos.write(bis.read());
            }
            bis.close();
            bos.close();
            fos.close();
            LoggerKt.d("share.png 保存图片成功");
            Uri shareUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", cacheFile);
            LoggerKt.d("url " + shareUri.toString());
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("image/*");
            intent.putExtra(Intent.EXTRA_STREAM, shareUri);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            context.startActivity(Intent.createChooser(intent, "分享"));
            runnable.run();
        } catch (Exception e) {
            LoggerKt.d(TAG + " 图片分享失败 : error => " + e.getMessage());
        }
    }
}
